﻿using ModbusTCP;
using S7.Net;
using S7.Net.Types;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AgvDemo
{
    public class JigouSinal
    {
        public JigouSinal()
        {

            Raster = 0;

            UpPlcLeave = 0;
            UpPlcAllowIn = 0;
            UpAgvArrive = 0;
            UpAgvLeave = 0;
            UpAgvError = 0;
            UpPlcError = 0;

            DownAgvLeave = 0;
            DownPlcAllowIn = 0;
            DownAgvArrive = 0;
            DownAgvError = 0;
            DownPlcError = 0;
            DownAgvRequest = 0;
        }

        public int Raster { get; set; }

        public int UpAgvArrive { get; set; }
        public int UpPlcLeave { get; set; }
        public int UpPlcAllowIn { get; set; }

        public int UpAgvLeave { get; set; }

        public int UpAgvError { get; set; }

        public int UpPlcError { get; set; }


        public int DownAgvLeave { get; set; }

        public int DownAgvArrive { get; set; }

        public int DownPlcAllowIn { get; set; }


        public int DownAgvRequest { get; set; }


        public int DownAgvError { get; set; }

        public int DownPlcError { get; set; }
    }

    public  class ModbusTcpClass
    {
        private Master MBmaster;
        public Ping pingAgv = new Ping();
        bool isConnectSure = false;
        string ip = null;
        public JigouSinal js = new JigouSinal();

        public int DoorUpAgv = 0;
        public int DoorDownAgv = 0;


        public int DoorUpLeaveControl = 0;
        public int DoorDownLeaveControl = 0;
        public ModbusTcpClass(string ipTemp)
        {
            ip = ipTemp;

            PlcThread();
        }


        public void PlcThread()
        {
            Thread th1 = new Thread(new ThreadStart(ChargeThreadMethod9));
            th1.IsBackground = true;
            th1.Start();

        }

        private void ChargeThreadMethod9()
        {

            while (true)
            {

                try
                {
                    if (pingAgv.Send(ip).Status == IPStatus.Success)
                    {
               
                        if (isConnectSure)
                        {



                            try
                            {
                                MBmaster.ReadHoldingRegister(3, 0, 7, 1);

                                Thread.Sleep(50);

                                MBmaster.ReadHoldingRegister(3, 9, 6, 1);
                            }
                            catch
                            { }


                            try
                            {
                                Thread.Sleep(50);

                                byte[] tempV = { 0, 1 };
                                MBmaster_Write(16, tempV);
                            }
                            catch
                            { }
                        }
                        else
                        {
                            try
                            {
                                MBmaster = new Master(ip, 502);
                                MBmaster.OnResponseData += new Master.ResponseData(MBmaster_OnResponseData);
                                MBmaster.OnException += new Master.ExceptionData(MBmaster_OnException);
                                isConnectSure = true;

                                MainForm.mainForm.toolStripLabel1.Text = "前装机构连接成功";
                                MainForm.mainForm.toolStripLabel1.ForeColor = Color.Lime;
                            }
                            catch
                            { isConnectSure = false;
                                MainForm.mainForm.toolStripLabel1.Text = "前装机构连接异常";
                                MainForm.mainForm.toolStripLabel1.ForeColor = Color.Red;
                            }

                        }
                    }
                    else
                    {
                  

                        try
                        {
                            if (MBmaster != null)
                                MBmaster.disconnect();
                        }
                        catch
                        { }


                        try
                        {
                            isConnectSure = false;
                          
                        }
                        catch
                        { }


                    }


                }
                catch
                {


                    try
                    {
                        if(MBmaster!=null)
                        MBmaster.disconnect();
                    }
                    catch
                    { }


                    try
                    {
                        isConnectSure = false;
                      
                    }
                    catch
                    { }

                }

                Thread.Sleep(300);
            }
        }


        private void MBmaster_OnResponseData(ushort ID, byte function, byte[] values)
        {
           
            if (ID == 0xFF) return;


            if (ID == 3)
            {
                int[] word = new int[1];

                if (values.Length < 13)
                {
                    word = new int[values.Length / 2];
                    for (int x = 0; x < values.Length; x = x + 2)
                    {
                        word[x / 2] = values[x] * 256 + values[x + 1];
                    }

                    js.DownAgvArrive = word[0];
                    js.DownPlcAllowIn = word[1];
                    js.DownAgvLeave = word[2];
                    js.DownAgvError = word[3];
                    js.DownPlcError = word[4];
                    js.DownAgvRequest = word[5];
                }
                else if (values.Length > 13)
                {
                    word = new int[values.Length / 2];
                    for (int x = 0; x < values.Length; x = x + 2)
                    {
                        word[x / 2] = values[x] * 256 + values[x + 1];
                    }

                    js.UpPlcAllowIn = word[0];
                    js.UpAgvArrive = word[1];

                    js.UpPlcLeave = word[2];
                    js.UpAgvLeave = word[3];

                    js.UpAgvError = word[4];
                    js.UpPlcError = word[5];

                    js.Raster = word[6];

                }


            }
            // ------------------------------------------------------------------------

        }

        // ------------------------------------------------------------------------
        // Modbus TCP slave exception 从站连接失败、故障反馈
        // ------------------------------------------------------------------------
        private void MBmaster_OnException(ushort id, byte function, byte exception)
        {
          

            string exc = "Modbus says error: ";
            switch (exception)
            {
                case Master.excIllegalFunction: exc += "Illegal function!"; break;
                case Master.excIllegalDataAdr: exc += "Illegal data adress!"; break;
                case Master.excIllegalDataVal: exc += "Illegal data value!"; break;
                case Master.excSlaveDeviceFailure: exc += "Slave device failure!"; break;
                case Master.excAck: exc += "Acknoledge!"; break;
                case Master.excSlaveIsBusy: exc += "Slave is busy!"; break;
                case Master.excGatePathUnavailable: exc += "Gateway path unavailbale!"; break;
                case Master.excExceptionTimeout: exc += "Slave timed out!"; break;
                case Master.excExceptionConnectionLost: exc += "Connection is lost!"; break;
                case Master.excExceptionNotConnected: exc += "Not connected!"; break;
            }

            isConnectSure = false;
        }


        public void MBmaster_Write(ushort start, byte[] value)
        {
            MBmaster.WriteSingleRegister(7, start, value);
        }


    }
}
